package cfengMiddleware.server.config;

import lombok.RequiredArgsConstructor;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/9/20
 * 自定义配置CuratorFramework对象用来实现Zookeeper的快速操作使用
 */

@Configuration
@RequiredArgsConstructor
public class ZooKeeperConfig {

    private final Environment environment;

    /**
     * 自定义注入Bean-Zookeeper高度封装的客户端Curator实例
     * 采用工厂模式进行创建，指定客户端连接到Zookeeper服务端的策略： 采用重试机制 5次，每次间隔1s 100ms
     */
    @Bean
    public CuratorFramework curatorFramework() {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(Objects.requireNonNull(environment.getProperty("zk.host"))).namespace(Objects.requireNonNull(environment.getProperty("zk.namespace")))
                .retryPolicy(new RetryNTimes(5,1000)).build();
        curatorFramework.start();
        return curatorFramework;
    }
}
